package com.bjb.util;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PictureCompressUtil {

    /**
     * base64图片压缩
     * @param base64Data
     * @param maxSize
     * @param suffixName
     * @return
     * @throws IOException
     */
    public static String doCompress(String base64Data, int maxSize, String suffixName) throws IOException {
        System.out.println(DateUtil.timestampDate(String.valueOf(System.currentTimeMillis())));
        String returnData = "";
        int base64FileSize = Base64ImageUtil.isBase64ImageSizeLegal(base64Data);
        System.out.println(maxSize);
        System.out.println(base64FileSize);
        if (base64FileSize > maxSize) {
            float scale = (float)maxSize / (float)base64FileSize;
            BufferedImage bufferedImage = Base64ImageUtil.base64StringToBufferedImage(base64Data);
            BufferedImage newBufferedImage = Thumbnails.of(bufferedImage).scale(scale).asBufferedImage();
            returnData = Base64ImageUtil.imageToBase64(newBufferedImage, suffixName);
            while (Base64ImageUtil.isBase64ImageSizeLegal(returnData) > maxSize){
                newBufferedImage = Thumbnails.of(newBufferedImage).scale(0.9f).asBufferedImage();
                returnData = Base64ImageUtil.imageToBase64(newBufferedImage, suffixName);
            }

        } else {
            returnData = base64Data;
        }
        System.out.println(DateUtil.timestampDate(String.valueOf(System.currentTimeMillis())));
        return returnData;
    }

    public static void main(String[] args) throws IOException{
        File file = new File("H:/test.jpg");
        BufferedImage read = ImageIO.read(file);
        String toBase64 = Base64ImageUtil.imageToBase64(read, "jpg");
        System.out.println(toBase64.length());
        String returnData = doCompress(toBase64, 4194304, "jpg");
//        System.out.println(returnData);
    }
}
